<template>
  <div id="addFilePage">
    <h2 style="margin-bottom: 16px">
      {{ route.query?.id ? '修改文件' : '创建文件' }}
    </h2>
    <!--    文件上传组件-->
    <FileUpload :file="file" :onSuccess="onSuccess" />

    <div style="margin-bottom: 16px" />
    <!--    文件信息表单-->
    <a-tabs v-model:activeKey="uploadType" v-if="file">
      <a-tab-pane key="file" tab="文件基本信息">
        <!--          文件信息更新-->
        <h2
          v-if="
            file.fillStatus === FILE_CREATE_STATUS_ENUM.RUNNING ||
            file.fillStatus === FILE_CREATE_STATUS_ENUM.WAITING
          "
          style="width: 100%; text-align: center; margin-top: 50px"
        >
          <LoadingOutlined />
          文件正在初始化请稍后再试
        </h2>
        <h2
          v-else-if="file.fillStatus === FILE_CREATE_STATUS_ENUM.ERROR"
          style="width: 100%; text-align: center; margin-top: 50px"
        >
          <CloseOutlined />
          文件初始化出现错误，请重新上传
        </h2>
        <a-form v-else name="fileForm" layout="vertical" :model="fileForm" @finish="handleSubmit">
          <a-row :wrap="false" style="font-size: 18px; margin-bottom: 10px">
            <a-col flex="auto">
              实例数：
              {{ file.instances ?? '--' }}
            </a-col>
            <a-col flex="auto">
              特征数：
              {{ file.features ?? '--' }}
            </a-col>
          </a-row>
          <a-form-item name="name" label="名称">
            <a-input v-model:value="fileForm.name" placeholder="请输入图片名称" allow-clear />
          </a-form-item>
          <a-form-item name="introduction" label="简介">
            <a-textarea
              v-model:value="fileForm.introduction"
              placeholder="请输入简介"
              :auto-size="{ minRows: 2, maxRows: 5 }"
              allow-clear
            />
          </a-form-item>
          <a-form-item name="category" label="分类">
            <a-auto-complete
              v-model:value="fileForm.category"
              placeholder="请输入分类"
              :options="categoryOptions"
              allow-clear
            />
          </a-form-item>
          <a-form-item name="tags" label="标签">
            <a-select
              v-model:value="fileForm.tags"
              mode="tags"
              :options="tagOptions"
              placeholder="请输入标签"
              allow-clear
            />
          </a-form-item>
          <a-form-item>
            <a-button type="primary" html-type="submit" style="width: 100%">更新基本信息</a-button>
          </a-form-item>
        </a-form>
      </a-tab-pane>

      <a-tab-pane key="variables" tab="文件变量信息" force-render>
        <!--        文件变量信息更新-->
        <h2
          v-if="
            file.fillStatus === FILE_CREATE_STATUS_ENUM.RUNNING ||
            file.fillStatus === FILE_CREATE_STATUS_ENUM.WAITING
          "
          style="width: 100%; text-align: center; margin-top: 50px"
        >
          <LoadingOutlined />
          文件正在初始化请稍后再试
        </h2>
        <h2
          v-else-if="file.fillStatus === FILE_CREATE_STATUS_ENUM.ERROR"
          style="width: 100%; text-align: center; margin-top: 50px"
        >
          <CloseOutlined />
          文件初始化出现错误，请重新上传
        </h2>
        <VariablesTable
          v-else
          :data-list="variablesList"
          :columns="columns"
          :show-op="true"
          :on-edit="getFileVariables"
          :pagination="pagination"
          :change="doTableChange"
        />
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, h, watchEffect } from 'vue'
import { message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import {
  editFileUsingPost,
  getFileVoByIdUsingGet,
  listFileTagCategoryUsingGet,
} from '@/api/fileController.ts'
import FileUpload from '@/components/FileUpload.vue'
import VariablesTable from '@/components/VariablesTable.vue'
import { listFileVariablesVoByPageUsingPost } from '@/api/fileVariablesController.ts'
import { LoadingOutlined, CloseOutlined } from '@ant-design/icons-vue'
import { FILE_CREATE_STATUS_ENUM } from '@/constant/file.ts'

const file = ref<API.FileVO>()
const fileForm = reactive<API.FileEditRequest>({})

const uploadType = ref<'file' | 'variables'>('file')

const onSuccess = (newFile: API.FileVO) => {
  file.value = newFile
  fileForm.name = newFile.name
  router.push({
    path: `/add_file`,
    query: { id: newFile.id }
  })
}
const route = useRoute()

const router = useRouter()

const handleSubmit = async (values: any) => {
  const fileId = file.value.id
  if (!fileId) {
    return
  }

  const res = await editFileUsingPost({
    id: fileId,
    ...values,
  })
  // 操作成功
  if (res.data.code === 0 && res.data.data) {
    message.success('更新成功')
  } else {
    message.error('更新失败，' + res.data.message)
  }
}

const categoryOptions = ref<string[]>([])
const tagOptions = ref<string[]>([])

/**
 * 获取标签和分类选项
 * @param values
 */
const getTagCategoryOptions = async () => {
  const res = await listFileTagCategoryUsingGet()
  // 操作成功
  if (res.data.code === 0 && res.data.data) {
    tagOptions.value = (res.data.data.tagList ?? []).map((data: string) => {
      return {
        value: data,
        label: data,
      }
    })
    categoryOptions.value = (res.data.data.categoryList ?? []).map((data: string) => {
      return {
        value: data,
        label: data,
      }
    })
  } else {
    message.error('获取标签分类失败，' + res.data.message)
  }
}

onMounted(() => {
  getTagCategoryOptions()
})

// 获取老数据
const getOldFile = async () => {
  // 获取到id
  const id = route.query?.id
  if (id) {
    const res = await getFileVoByIdUsingGet({
      id,
    })
    if (res.data.code === 0 && res.data.data) {
      const data = res.data.data
      file.value = data
      fileForm.name = data.name
      fileForm.introduction = data.introduction
      fileForm.category = data.category
      fileForm.tags = data.tags
    }
  }
}
const variablesList = ref<API.FileVariablesVO[]>([])

const variablesTotal = ref(0)

const columns = [
  {
    title: 'column',
    dataIndex: 'columnNumber',
    width: '9%',
  },
  {
    title: 'name',
    dataIndex: 'name',
  },
  {
    title: 'role',
    dataIndex: 'role',
  },
  {
    title: 'type',
    dataIndex: 'type',
  },
  {
    title: 'description',
    dataIndex: 'description',
  },
  {
    title: 'units',
    dataIndex: 'units',
  },
  {
    title: 'missing',
    dataIndex: 'missing',
  },
  {
    title: 'operation',
    dataIndex: 'operation',
  },
]

const searchVariablesParams = reactive<API.FileVariablesQueryRequest>({
  current: 1,
  pageSize: 8,
  sortField: 'columnNumber',
  sortOrder: 'ascend',
}) // 局部更新

const getFileVariables = async () => {
  // 获取到id
  const id = route.query?.id
  if (id) {
    searchVariablesParams.fileId = id
    const res = await listFileVariablesVoByPageUsingPost(searchVariablesParams)
    if (res.data.code === 0 && res.data.data) {
      variablesList.value = res.data.data.records ?? []
      variablesTotal.value = res.data.data.total ?? 0
    }
  }
}

const pagination = computed(() => {
  return {
    current: searchVariablesParams.current,
    pageSize: searchVariablesParams.pageSize,
    total: variablesTotal.value,
    showSizeChanger: true,
    showTotal: (total) => `共${total}条`,
  }
})

//表格变化，然后重新获取数据
const doTableChange = (page: any) => {
  searchVariablesParams.current = page.current
  searchVariablesParams.pageSize = page.pageSize
  getFileVariables()
}

onMounted(() => {
  getOldFile()
  getFileVariables()
})
</script>

<style scoped>
#addFilePage {
  max-width: 1000px;
  margin: 0 auto;
}
#addFilePage .edit-bar {
  text-align: center;
  margin: 16px 0;
}
</style>
